package com.zhangyu.shadow.ec.main.cart;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.joanzapata.iconify.widget.IconTextView;
import com.zhangyu.shadow.core.delegate.bottom.BottomItemDelegate;
import com.zhangyu.shadow.core.net.RestClient;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.util.log.ShadowLogger;
import com.zhangyu.shadow.ec.R;
import com.zhangyu.shadow.ec.R2;
import com.zhangyu.shadow.ec.pay.FastPay;
import com.zhangyu.shadow.ec.pay.IPayResultListener;

import java.text.DecimalFormat;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zhangyu
 * @date 2017/11/13
 */

public class ShopCartDelegate extends BottomItemDelegate implements ISuccess, IPayResultListener {
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.icon_shop_cart_select_all)
    IconTextView mITvSelectAll;
    @BindView(R2.id.tv_total_price)
    TextView mTvMoney;
    private int mColorSelect;
    private int mColorNormal;
    private ShopCartAdapter mShopCartAdapter;

    @Override
    public Object setLayout() {
        return R.layout.delegate_shop_cart;
    }

    @OnClick(R2.id.icon_shop_cart_select_all)
    public void onItemSelectAll() {
        ShopItemSelectFlag tag = (ShopItemSelectFlag) mITvSelectAll.getTag();
        if (tag == ShopItemSelectFlag.SELECT_NONE ||
                tag == ShopItemSelectFlag.INIT) {
            mITvSelectAll.setTextColor(mColorSelect);
            mITvSelectAll.setTag(ShopItemSelectFlag.SELECT_ALL);
            mShopCartAdapter.setItemSelectFlag(ShopItemSelectFlag.SELECT_ALL);
            mShopCartAdapter.notifyItemRangeChanged(0, mShopCartAdapter.getItemCount());
            mShopCartAdapter.selectAllItem();
        } else {
            mITvSelectAll.setTextColor(mColorNormal);
            mITvSelectAll.setTag(ShopItemSelectFlag.SELECT_NONE);
            mShopCartAdapter.setItemSelectFlag(ShopItemSelectFlag.SELECT_NONE);
            mShopCartAdapter.notifyItemRangeChanged(0, mShopCartAdapter.getItemCount());
            mShopCartAdapter.unSelectAllItem();
        }
    }

    @OnClick(R2.id.tv_clear)
    public void onClearShopCart() {
        mShopCartAdapter.clearAllItems();
    }

    @OnClick(R2.id.tv_delete)
    public void onDeleteSelectItem() {
        mShopCartAdapter.deleteSelectItems();
    }

    @OnClick(R2.id.tv_close_account)
    public void onClickPay() {
        createOrder();
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mITvSelectAll.setTag(ShopItemSelectFlag.INIT);
        mColorSelect = ContextCompat.getColor(getContext(), R.color.app_main);
        mColorNormal = Color.GRAY;
        initRecyclerView();
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //避免闪屏
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        RestClient.builder()
                .url("shop_cart.php")
                .success(this)
                .build()
                .get();
    }

    @Override
    public void onSuccess(String response) {
        final String rmb = getString(R.string.RMB);
        final DecimalFormat df = new DecimalFormat("######0.00");
        mShopCartAdapter = new ShopCartAdapter(new ShopCartDataConverter().
                setJsonData(response).convert(), mColorSelect, mColorNormal, new ShopCartAdapter.OnItemSelectChangeListener() {
            @Override
            public void onChange() {
                final int selectDataSize = mShopCartAdapter.getSelectDataSize();
                final int allSize = mShopCartAdapter.getAllDataSize();
                if (selectDataSize != 0 && selectDataSize == allSize) {
                    mITvSelectAll.setTag(ShopItemSelectFlag.SELECT_ALL);
                    mITvSelectAll.setTextColor(mColorSelect);
                } else if (selectDataSize == 0) {
                    mITvSelectAll.setTag(ShopItemSelectFlag.SELECT_NONE);
                    mITvSelectAll.setTextColor(mColorNormal);
                } else {
                    mITvSelectAll.setTag(ShopItemSelectFlag.INIT);
                    mITvSelectAll.setTextColor(mColorNormal);
                }
                double currentTotalMoney = mShopCartAdapter.getCurrentTotalMoney();
                mTvMoney.setText(String.format(rmb, df.format(currentTotalMoney)));
            }
        });
        mRecyclerView.setAdapter(mShopCartAdapter);
        mShopCartAdapter.bindToRecyclerView(mRecyclerView);
        mShopCartAdapter.setEmptyView(R.layout.item_shop_cart_empty);
        mShopCartAdapter.filterSelectDataFromAllData();

    }

    /**
     * 将商品参数传递给服务器，服务器负责生成订单信息
     * 客户端拿到订单信息调起支付宝sdk支付接口进行支付
     */
    private void createOrder() {
        final String orderUrl = "你的生成订单的API";
        final WeakHashMap<String, Object> orderParams = new WeakHashMap<>();
        //加入你的参数
        RestClient.builder()
                .url(orderUrl)
                .loader(getContext())
                .params(orderParams)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        //进行具体的支付
                        ShadowLogger.d("ORDER", response);
                        final int orderId = JSON.parseObject(response).getInteger("result");
                        FastPay.create(ShopCartDelegate.this)
                                .setPayResultListener(ShopCartDelegate.this)
                                .setOrderId(orderId)
                                .beginPayDialog();
                    }
                })
                .build()
                .post();
    }

    @Override
    public void onPaySuccess() {

    }

    @Override
    public void onPaying() {

    }

    @Override
    public void onPayCancel() {

    }

    @Override
    public void onPayFailed() {

    }

    @Override
    public void onPayConnectError() {

    }
}
